<template>
  <div class="dashboard-container">
    <div class="dashboard-header">
      <h1 class="dashboard-title">慢病与肿瘤数据大屏</h1>
      <div class="update-time">
        最后更新时间: {{ updateTime }}
      </div>
    </div>

    <div class="dashboard-content">
      <!-- 统计卡片区域 -->
      <div class="stats-cards">
        <el-row :gutter="20">
          <el-col :span="6" v-for="stat in statsData" :key="stat.title">
            <el-card class="stat-card" shadow="hover">
              <div class="stat-content">
                <div class="stat-icon" :style="{ backgroundColor: stat.color }">
                  <el-icon :size="24">
                    <component :is="stat.icon" />
                  </el-icon>
                </div>
                <div class="stat-info">
                  <div class="stat-value">{{ stat.value }}</div>
                  <div class="stat-title">{{ stat.title }}</div>
                  <div class="stat-trend" :class="stat.trend > 0 ? 'positive' : 'negative'">
                    <el-icon><component :is="stat.trend > 0 ? 'ArrowUp' : 'ArrowDown'" /></el-icon>
                    {{ Math.abs(stat.trend) }}%
                  </div>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 图表区域 -->
      <div class="charts-section">
        <el-row :gutter="20">
          <!-- 病例趋势图 -->
          <el-col :span="12">
            <el-card class="chart-card" shadow="hover">
              <template #header>
                <div class="card-header">
                  <span>病例趋势分析</span>
                  <el-select v-model="trendPeriod" size="small" style="width: 120px">
                    <el-option label="近7天" value="7d" />
                    <el-option label="近30天" value="30d" />
                    <el-option label="近3个月" value="3m" />
                  </el-select>
                </div>
              </template>
              <div class="chart-container" ref="trendChartRef"></div>
            </el-card>
          </el-col>

          <!-- 疾病分布饼图 -->
          <el-col :span="12">
            <el-card class="chart-card" shadow="hover">
              <template #header>
                <span>疾病类型分布</span>
              </template>
              <div class="chart-container" ref="pieChartRef"></div>
            </el-card>
          </el-col>
        </el-row>

        <el-row :gutter="20" style="margin-top: 20px">
          <!-- 年龄分布柱状图 -->
          <el-col :span="12">
            <el-card class="chart-card" shadow="hover">
              <template #header>
                <span>患者年龄分布</span>
              </template>
              <div class="chart-container" ref="ageChartRef"></div>
            </el-card>
          </el-col>

          <!-- 治疗效果统计 -->
          <el-col :span="12">
            <el-card class="chart-card" shadow="hover">
              <template #header>
                <span>治疗效果统计</span>
              </template>
              <div class="chart-container" ref="effectChartRef"></div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 实时数据流 -->
      <div class="realtime-section">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>实时数据监控</span>
              <el-tag :type="isRealTimeActive ? 'success' : 'danger'">
                {{ isRealTimeActive ? '实时更新中' : '已暂停' }}
              </el-tag>
            </div>
          </template>
          <div class="realtime-content">
            <el-table :data="realtimeData" height="300">
              <el-table-column prop="time" label="时间" width="180" />
              <el-table-column prop="type" label="类型" width="120">
                <template #default="{ row }">
                  <el-tag :type="getTypeColor(row.type)">{{ row.type }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="patient" label="患者信息" />
              <el-table-column prop="action" label="操作" />
              <el-table-column prop="status" label="状态" width="100">
                <template #default="{ row }">
                  <el-tag :type="row.status === '成功' ? 'success' : 'warning'">
                    {{ row.status }}
                  </el-tag>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { ArrowUp, ArrowDown, User, Document, Calendar, DataAnalysis } from '@element-plus/icons-vue'
import * as echarts from 'echarts'

// 响应式数据
const updateTime = ref('')
const trendPeriod = ref('7d')
const isRealTimeActive = ref(true)

// 图表引用
const trendChartRef = ref()
const pieChartRef = ref()
const ageChartRef = ref()
const effectChartRef = ref()

// 统计数据
const statsData = ref([
  {
    title: '慢病患者总数',
    value: '1,234',
    trend: 12.5,
    color: '#409EFF',
    icon: 'User'
  },
  {
    title: '肿瘤患者总数',
    value: '856',
    trend: 8.3,
    color: '#67C23A',
    icon: 'Document'
  },
  {
    title: '本月新增',
    value: '142',
    trend: -2.1,
    color: '#E6A23C',
    icon: 'Calendar'
  },
  {
    title: '随访完成率',
    value: '89.6%',
    trend: 5.7,
    color: '#F56C6C',
    icon: 'DataAnalysis'
  }
])

// 实时数据
const realtimeData = ref([
  {
    time: '2024-01-15 14:30:25',
    type: '慢病登记',
    patient: '张三 (ID: 001234)',
    action: '新增糖尿病患者',
    status: '成功'
  },
  {
    time: '2024-01-15 14:28:15',
    type: '随访记录',
    patient: '李四 (ID: 001235)',
    action: '高血压随访完成',
    status: '成功'
  },
  {
    time: '2024-01-15 14:25:42',
    type: '肿瘤筛查',
    patient: '王五 (ID: 001236)',
    action: '肺癌筛查异常',
    status: '待处理'
  }
])

// 定时器
let updateTimer: number
let trendChart: echarts.ECharts | null = null
let pieChart: echarts.ECharts | null = null
let ageChart: echarts.ECharts | null = null
let effectChart: echarts.ECharts | null = null

const updateCurrentTime = () => {
  const now = new Date()
  updateTime.value = now.toLocaleString('zh-CN')
}

// 初始化图表
const initCharts = async () => {
  await nextTick()
  
  // 病例趋势图
  if (trendChartRef.value) {
    trendChart = echarts.init(trendChartRef.value)
    const trendOption = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross'
        }
      },
      legend: {
        data: ['慢病患者', '肿瘤患者']
      },
      xAxis: {
        type: 'category',
        data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月']
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          name: '慢病患者',
          type: 'line',
          data: [120, 132, 101, 134, 90, 230, 210],
          smooth: true,
          itemStyle: {
            color: '#409EFF'
          }
        },
        {
          name: '肿瘤患者',
          type: 'line',
          data: [220, 182, 191, 234, 290, 330, 310],
          smooth: true,
          itemStyle: {
            color: '#67C23A'
          }
        }
      ]
    }
    trendChart.setOption(trendOption)
  }

  // 疾病分布饼图
  if (pieChartRef.value) {
    pieChart = echarts.init(pieChartRef.value)
    const pieOption = {
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 'left'
      },
      series: [
        {
          name: '疾病分布',
          type: 'pie',
          radius: '50%',
          data: [
            { value: 435, name: '糖尿病' },
            { value: 310, name: '高血压' },
            { value: 234, name: '肺癌' },
            { value: 135, name: '胃癌' },
            { value: 156, name: '其他慢病' }
          ],
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    }
    pieChart.setOption(pieOption)
  }

  // 年龄分布柱状图
  if (ageChartRef.value) {
    ageChart = echarts.init(ageChartRef.value)
    const ageOption = {
      tooltip: {
        trigger: 'axis'
      },
      xAxis: {
        type: 'category',
        data: ['0-18岁', '19-30岁', '31-45岁', '46-60岁', '61-75岁', '75岁以上']
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          name: '患者数量',
          type: 'bar',
          data: [12, 45, 128, 312, 456, 234],
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#83bff6' },
              { offset: 0.5, color: '#188df0' },
              { offset: 1, color: '#188df0' }
            ])
          }
        }
      ]
    }
    ageChart.setOption(ageOption)
  }

  // 治疗效果统计
  if (effectChartRef.value) {
    effectChart = echarts.init(effectChartRef.value)
    const effectOption = {
      tooltip: {
        trigger: 'item'
      },
      legend: {
        top: '5%',
        left: 'center'
      },
      series: [
        {
          name: '治疗效果',
          type: 'pie',
          radius: ['40%', '70%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: '40',
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: [
            { value: 1048, name: '显著改善' },
            { value: 735, name: '有所改善' },
            { value: 580, name: '病情稳定' },
            { value: 484, name: '无明显变化' },
            { value: 300, name: '病情恶化' }
          ]
        }
      ]
    }
    effectChart.setOption(effectOption)
  }
}

// 图表自适应
const resizeCharts = () => {
  trendChart?.resize()
  pieChart?.resize()
  ageChart?.resize()
  effectChart?.resize()
}

const getTypeColor = (type: string) => {
  const colorMap: Record<string, string> = {
    '慢病登记': 'primary',
    '随访记录': 'success',
    '肿瘤筛查': 'warning'
  }
  return colorMap[type] || 'info'
}

// 模拟实时数据更新
const simulateRealTimeData = () => {
  if (!isRealTimeActive.value) return
  
  const types = ['慢病登记', '随访记录', '肿瘤筛查']
  const patients = ['张三', '李四', '王五', '赵六', '钱七']
  const actions = ['新增患者记录', '完成随访', '异常筛查结果', '治疗方案更新']
  const statuses = ['成功', '待处理']
  
  const newData = {
    time: new Date().toLocaleString('zh-CN'),
    type: types[Math.floor(Math.random() * types.length)],
    patient: `${patients[Math.floor(Math.random() * patients.length)]} (ID: ${Math.floor(Math.random() * 999999).toString().padStart(6, '0')})`,
    action: actions[Math.floor(Math.random() * actions.length)],
    status: statuses[Math.floor(Math.random() * statuses.length)]
  }
  
  realtimeData.value.unshift(newData)
  if (realtimeData.value.length > 10) {
    realtimeData.value.pop()
  }
}

onMounted(() => {
  updateCurrentTime()
  initCharts()
  
  updateTimer = setInterval(() => {
    updateCurrentTime()
    simulateRealTimeData()
  }, 5000)

  // 监听窗口大小变化
  window.addEventListener('resize', resizeCharts)
})

onUnmounted(() => {
  if (updateTimer) {
    clearInterval(updateTimer)
  }
  
  // 清理图表实例
  trendChart?.dispose()
  pieChart?.dispose()
  ageChart?.dispose()
  effectChart?.dispose()
  
  // 移除事件监听
  window.removeEventListener('resize', resizeCharts)
})
</script>

<style lang="scss" scoped>
.dashboard-container {
  padding: 0;
}

.dashboard-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 20px;
  background: linear-gradient(135deg, #409EFF 0%, #36D1DC 100%);
  border-radius: 8px;
  color: white;

  .dashboard-title {
    font-size: 28px;
    font-weight: 600;
    margin: 0;
  }

  .update-time {
    font-size: 14px;
    opacity: 0.9;
  }
}

.dashboard-content {
  .stats-cards {
    margin-bottom: 24px;

    .stat-card {
      height: 120px;
      cursor: pointer;
      transition: all 0.3s ease;

      &:hover {
        transform: translateY(-4px);
        box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
      }

      .stat-content {
        display: flex;
        align-items: center;
        height: 100%;

        .stat-icon {
          width: 60px;
          height: 60px;
          border-radius: 12px;
          display: flex;
          align-items: center;
          justify-content: center;
          color: white;
          margin-right: 16px;
        }

        .stat-info {
          flex: 1;

          .stat-value {
            font-size: 28px;
            font-weight: 700;
            color: #303133;
            line-height: 1;
            margin-bottom: 4px;
          }

          .stat-title {
            font-size: 14px;
            color: #909399;
            margin-bottom: 8px;
          }

          .stat-trend {
            display: flex;
            align-items: center;
            font-size: 12px;
            font-weight: 600;

            &.positive {
              color: #67C23A;
            }

            &.negative {
              color: #F56C6C;
            }

            .el-icon {
              margin-right: 2px;
            }
          }
        }
      }
    }
  }

  .charts-section {
    margin-bottom: 24px;

    .chart-card {
      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        font-weight: 600;
        color: #303133;
      }

      .chart-container {
        height: 300px;
        width: 100%;
      }
    }
  }

  .realtime-section {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-weight: 600;
      color: #303133;
    }

    .realtime-content {
      :deep(.el-table) {
        .el-table__header {
          background: #f8f9fa;
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 1200px) {
  .dashboard-header {
    .dashboard-title {
      font-size: 24px;
    }
  }
}

@media (max-width: 768px) {
  .dashboard-header {
    flex-direction: column;
    gap: 12px;
    text-align: center;

    .dashboard-title {
      font-size: 20px;
    }
  }

  .stats-cards {
    :deep(.el-col) {
      margin-bottom: 16px;
    }
  }
}
</style>